package nl.boelen.game.server.connection;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import nl.boelen.game.net.packet.Packet;
import nl.boelen.game.server.entity.PlayerMP;

public class ServerTCPSender {

    public ServerTCPSender() {
    }

    public void sendPacket(PlayerMP player, Packet packet) {
        sendPacket(packet, player.getIp(), player.getTCPPort());
    }

    public void sendPacket(final Packet packet, final InetAddress address, final int port) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                byte[] data = packet.getData();
                try (Socket socket = new Socket(address, port)) {
                    try (DataOutputStream out = new DataOutputStream(socket.getOutputStream())) {
                        try (DataInputStream in = new DataInputStream(socket.getInputStream())) {
                            // Send
                            out.writeInt(data.length);
                            out.write(data);
                            out.flush();
                            // Receive
                            int size = in.readInt();
                            byte[] response = new byte[size];
                            if (size > 0) {
                                in.readFully(response);

                                String serverResponse = new String(response).trim();
                                if (!serverResponse.equalsIgnoreCase("ok")) {
                                    // Something went wrong
                                }
                            }
                        }
                    }
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();
    }
}
